package com.iteaj.iot.taos;

import com.iteaj.iot.taos.proxy.TaosHandleProxyMatcher;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.sql.DataSource;

/**
 * create time: 2022/1/18
 *
 * @author iteaj
 * @since 1.0
 */
@Configuration
@EnableScheduling
@EnableConfigurationProperties(IotTaosProperties.class)
public class IotTaosAutoConfiguration implements BeanFactoryAware {

    public static BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        IotTaosAutoConfiguration.beanFactory = beanFactory;
    }

    @Configuration
    @AutoConfigureAfter(DataSourceAutoConfiguration.class)
    public static class TaosDataSourceConfiguration {

        @Bean
        @ConditionalOnMissingBean(name = "taosJdbcTemplate")
        public JdbcTemplate taosJdbcTemplate(DataSource taosDataSource) {
            return IotTaos.databaseSource.taosJdbcTemplate = new JdbcTemplate(taosDataSource);
        }

        @Bean
        @ConditionalOnMissingBean(name = "taosDataSource")
        public DataSource taosDataSource(IotTaosProperties properties) {
            if(properties.getDatasource() == null) {
                throw new BeanCreationException("未配置数据源[iot.taos.datasource.xx]");
            }
            return properties.getDatasource().build();
        }
    }

    @Bean
    @ConditionalOnMissingBean(TaosSqlManager.class)
    public TaosSqlManager taosSqlManager() {
        return new DefaultTaosSqlManager();
    }

    @Bean
    @Order(10000)
    @ConditionalOnBean(TaosHandle.class)
    @ConditionalOnMissingBean(TaosHandleProxyMatcher.class)
    public TaosHandleProxyMatcher taosHandleProxyMatcher(TaosSqlManager taosSqlManager) {
        return new TaosHandleProxyMatcher(taosSqlManager);
    }

}
